package br.com.future.controllers;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

import br.com.future.constants.UptimeSingleton;
import br.com.future.model.PingResponse;

/**
 * This controller shall be used to collect informations about the server.<br>
 * For now we will only share the uptime information, but in a future moment some cool staticstics like:<br>
 * % CPU usage % memory usage Load-average
 * 
 * @author Rafael Castanho Ferreira (mailto: rafa.ferreira@gmail.com)
 * @since 03-2011
 */
public class PingController implements Controller {

	private static final Log LOG = LogFactory.getLog(PingController.class);

	/**
	 * This method will be auto-magically called by Spring.
	 * Check PingController bean definition to see how is the trigger for this magic!
	 */
	public void init() {
		UptimeSingleton.getInstance();

		if (LOG.isDebugEnabled())
			LOG.debug("PingController initialized - UptimeSingleton inicialized NOW!");
	}

	public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {

		if (LOG.isDebugEnabled())
			LOG.debug("Entering PingController");

		UptimeSingleton.getInstance();

		response.setStatus(HttpServletResponse.SC_OK);
		response.setContentType("application/json; charset=UTF-8");

		PingResponse pingResponse = new PingResponse();
		pingResponse.setSucceed(true);
		pingResponse.setHttpCode(HttpServletResponse.SC_OK);
		pingResponse.setUptime(System.currentTimeMillis() - UptimeSingleton.getStartupTime());
		ControllerHelper.marshallObjectToJson(pingResponse, response.getOutputStream());

		LOG.info("PingController called - returning with: " + pingResponse.toString());
		return null;
	}
}
